import entity.User;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Version :
 * @PROJECT_NAME: java-basics
 * @PACKAGE_NAME:PACKAGE_NAME
 * @NAME: Dom4jPaser
 * @author:xuandian
 * @DATE: 2022/6/26 0:03
 * @description:
 */


public class Dom4jPaser implements Parser {
    @Override
    public User[] parse(String url) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document read = reader.read(new File(url));
        Element rootElement = read.getRootElement();
        List<Element> book = rootElement.elements("user");
        List<User> userList = new ArrayList<>();
        for (Element books : book) {
            User user = new User();
            user.setUserId(Integer.parseInt(books.attributeValue("id")));
            user.setUserName(books.elementText("name"));
            userList.add(user);
        }
        User [] users=new User[userList.size()];
        return (User[])userList.toArray(users);
    }
    public static void main(String[] args) throws DocumentException {

        Parser parser=new Dom4jPaser();
        User[] users = parser.parse("userinfo.xml");
        System.out.println(Arrays.toString(users));
    }
}
